package com.example.element.module.netWork

import android.content.Context
import android.content.Intent
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActNetworkHttpurlConnnectionBinding
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class HttpUrlConnectionActivity : AbsActivity<ActNetworkHttpurlConnnectionBinding>() {

    companion object {
        @JvmStatic
        fun open(context: Context) {
            context.startActivity(Intent(context, HttpUrlConnectionActivity::class.java))
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.act_network_httpurl_connnection
    }

    override fun main() {

    }

    override fun initListener() {
       mBinding.btnHttpUrl.setOnClickListener {
           sendRequestWithHttpURLConnection()
       }
    }

    private fun sendRequestWithHttpURLConnection() {
        //开启线程发起请求
        thread {
            var connection: HttpURLConnection? = null
            try {
                val response = StringBuilder()
                val url = URL("https://www.baidu.com")
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 5000
                connection.readTimeout = 5000
                val input = connection.inputStream
                //读取流
                val reader = BufferedReader(InputStreamReader(input))
                reader.use {
                    reader.forEachLine {
                        response.append(it)
                    }
                    showResponse(response.toString())
                }
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                connection?.disconnect()
            }
        }
    }

    private fun showResponse(string: String) {
        runOnUiThread{
            mBinding.tvText.text=string
        }
    }
}